/// <reference path="./BaseSystem.ts" />
module ecs {
    export class AspectSubscriptionManager extends BaseSystem{
        private _subscriptionMap: Map<Builder, EntitySubscription>;
        private _subscriptions: Bag<EntitySubscription> = new Bag<EntitySubscription>();
        private _changed: NumberBag = new NumberBag();
        private _deleted: NumberBag = new NumberBag();

        constructor(){
            super();

            this._subscriptionMap = new Map<Builder, EntitySubscription>([]);
        }

        protected processSystem() {}

        /**
         * 通知所有侦听器已添加、更改的位和删除dbits更改。
         * @param changedBits 
         * @param deletedBits 
         */
        public processNotify(changedBits: BitVector, deletedBits: BitVector){
            this.toEntityIntBags(changedBits, deletedBits);
        }

        private toEntityIntBags(changed: BitVector, deleted: BitVector){
            changed.toIntBagIdCid(this._world.getComponentManager(), this._changed);
            deleted.toIntBag(this._deleted);

            changed.clear();
            deleted.clear();
        }

        public get(builder: Builder): EntitySubscription{
            let subscription = this._subscriptionMap.get(builder);
            return (subscription != null) ? subscription : this.createSubscription(builder);
        }

        private createSubscription(builder: Builder): EntitySubscription{
            let entitySubscription = new EntitySubscription(this._world, builder);
            this._subscriptionMap.add(builder, entitySubscription);
            this._subscriptions.add(entitySubscription);

            this._world.getComponentManager().synchronize(entitySubscription);

            return entitySubscription;
        }
    }
}